#!/usr/bin/env bash
# Copyright (c) 2021 The Toltec Contributors
# SPDX-License-Identifier: MIT

# Inspired by https://github.com/archlinux/svntogit-packages/blob/packages/tzdata/trunk/PKGBUILD

pkgnames=(zoneinfo-utils)
pkgdesc="Utilities for interacting with zoneinfo files"
url=https://www.iana.org/time-zones
_tzver=2023c
pkgver="$_tzver"-1
timestamp=2023-03-28T00:00Z
section=utils
maintainer="Eeems <eeems@eeems.email>"
license="custom: public domain"
installdepends=(zoneinfo-core)
makedepends=(build:gawk)
flags=(nostrip)

image=base:v3.0
source=(
    "https://www.iana.org/time-zones/repository/releases/tzcode${_tzver}.tar.gz"
    "https://www.iana.org/time-zones/repository/releases/tzdata${_tzver}.tar.gz"
)
sha256sums=(
    46d17f2bb19ad73290f03a203006152e0fa0d7b11e5b71467c4a823811b214e7
    3f510b5d1b4ae9bb38e485aa302a776b317fb3637bdb6404c4adf7b6cadd965c
)

prepare() {
    sed -i "s:sbin:bin:" Makefile
}

build() {
    mkdir .x86
    pushd .x86 > /dev/null

    shopt -s extglob
    ln -s ../* .
    make VERSION="$_tzver" zic
    mv zic ../zic.x86

    popd > /dev/null
    rm -r .x86
    make VERSION="$_tzver" CC=arm-linux-gnueabihf-cc
    "${CROSS_COMPILE}strip" --strip-all zic zdump
}

package() {
    pushd "${srcdir}" > /dev/null

    local zic=./zic.x86
    # install tzcode stuff
    make DESTDIR="${pkgdir}" zic="$zic" install
    # install license
    install -Dm644 LICENSE "${pkgdir}"/opt/usr/share/licenses/tzdata/LICENSE

    popd > /dev/null

    mv "${pkgdir}"/usr/{lib,share/man} "${pkgdir}"/opt/usr
    mv "${pkgdir}"/usr/{s,}bin "${pkgdir}"/opt

    install -D -m 644 -t "$pkgdir"/opt/share/zoneinfo "$srcdir"/iso3166.tab
    install -D -m 644 -t "$pkgdir"/opt/share/zoneinfo "$srcdir"/zone1970.tab

    # cleanup
    rm -rf "${pkgdir:?}"/{etc,usr}
}

configure() {
    add-bind-mount /home/root/.entware/share/zoneinfo \
        /usr/share/zoneinfo
}

postremove() {
    remove-bind-mount /usr/share/zoneinfo
}
